package com.yao.shop.service.impl;

import com.yao.shop.common.Page;
import com.yao.shop.constant.CoreConstant;
import com.yao.shop.enums.ResultEnums;
import com.yao.shop.exception.PochiException;
import com.yao.shop.mapper.ShopBrandCategoryMapper;
import com.yao.shop.mapper.ShopBrandMapper;
import com.yao.shop.mapper.ShopProductCategoryMapper;
import com.yao.shop.pojo.ShopBrand;
import com.yao.shop.pojo.ShopBrandCategory;
import com.yao.shop.pojo.ShopProductCategory;
import com.yao.shop.pojo.vo.CategoryBrandVo;
import com.yao.shop.pojo.vo.ShopProductCategoryVo;
import com.yao.shop.service.ShopProductCategoryService;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShopProductCategoryServiceImpl implements ShopProductCategoryService {
    @Autowired
    private ShopProductCategoryMapper shopProductCategoryMapper;
    @Autowired
    private ShopBrandCategoryMapper shopBrandCategoryMapper;
    @Autowired
    private ShopBrandMapper shopBrandMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ShopProductCategory shopProductCategory) {
        // 如果父级ID为空，就赋值为0
        if (shopProductCategory.getParentId() == null) {
            shopProductCategory.setParentId(CoreConstant.DEFAULT_PARENT_ID);
        }
        ShopProductCategory category = shopProductCategoryMapper.getByParentIdAndName(shopProductCategory);
        if (category != null) {
            throw new PochiException(ResultEnums.CATEGORY_EXISTS);
        }
        shopProductCategoryMapper.save(shopProductCategory);
    }

    @Override
    public void update(ShopProductCategory shopProductCategory) {
        // 如果父级ID为空，就赋值为0
        if (shopProductCategory.getParentId() == null) {
            shopProductCategory.setParentId(CoreConstant.DEFAULT_PARENT_ID);
        }
        // 如果没改名称，也没有改父级菜单的情况下，当前查出来的就是自己
        ShopProductCategory category = shopProductCategoryMapper.getByParentIdAndName(shopProductCategory);
        if (category != null && !category.getId().equals(shopProductCategory.getId())) {
            throw new PochiException(ResultEnums.CATEGORY_EXISTS);
        }
        shopProductCategoryMapper.update(shopProductCategory);
    }

    @Override
    public ShopProductCategory get(Long id) {
        return shopProductCategoryMapper.get(id);
    }

    @Override
    public void delete(Long id) {
        shopProductCategoryMapper.delete(id);
    }

    @Override
    public Page<ShopProductCategory> getByPage(Page<ShopProductCategory> page) {
        List<ShopProductCategory> list = shopProductCategoryMapper.getByPage(page);
        Integer totalCount = shopProductCategoryMapper.countByPage(page);
        page.setList(list);
        page.setTotalCount(totalCount);
        return page;
    }

    @Override
    public List<ShopProductCategoryVo> getTree() {
        // 查询出所有
        List<ShopProductCategory> list = shopProductCategoryMapper.getAll();
        // 找到父节点
        return buildTree(list);
    }

    @Override
    public List<ShopProductCategoryVo> getSelectTree() {
        // 查询出所有非三级分类
        List<ShopProductCategory> list = shopProductCategoryMapper.getSelectList();
        return buildTree(list);
    }

    @Override
    public List<ShopProductCategory> getAllSecond() {
        // 查询所有二级分类
        List<ShopProductCategory> secondList = shopProductCategoryMapper.getAllSecond();
        // 查询所有一级分类
        List<ShopProductCategory> topList = shopProductCategoryMapper.getAllTop();
        // 遍历一级分类和二级分类
        secondList.forEach(s -> {
            // 遍历一级分类，取出id和s.parentId相同的数据
            ShopProductCategory parent = topList.stream().filter(t -> t.getId().equals(s.getParentId())).findFirst().orElse(null);
            if (parent != null) {
                s.setName(parent.getName() + CoreConstant.CONCAT_NAME + s.getName());
            }
        });
        return secondList;
    }

    @Override
    public List<ShopProductCategory> getNavList() {
        return shopProductCategoryMapper.getNavList();
    }



    /**
     * 构造树形结构
     *
     * @param list
     * @return
     */
    private List<ShopProductCategoryVo> buildTree(List<ShopProductCategory> list) {
        return list.stream().filter(e -> e.getParentId().equals(CoreConstant.DEFAULT_PARENT_ID))
                .map(e -> {
                    // 构造成VO
                    ShopProductCategoryVo vo = new ShopProductCategoryVo();
                    BeanUtils.copyProperties(e, vo);
                    return vo;
                }).map(e -> {
                    // 构造子节点
                    e.setChildren(getChildren(e, list));
                    // 如果children是空，就设为null
                    if (CollectionUtils.isEmpty(e.getChildren())) {
                        e.setChildren(null);
                    }
                    return e;
                }).collect(Collectors.toList());
    }

    /**
     * 寻找子节点
     *
     * @param category
     * @param list
     * @return
     */
    private List<ShopProductCategoryVo> getChildren(ShopProductCategoryVo category, List<ShopProductCategory> list) {
        // 找到category所有的子节点
        return list.stream().filter(e -> e.getParentId().equals(category.getId()))
                .map(e -> {
                    // 转成VO
                    ShopProductCategoryVo vo = new ShopProductCategoryVo();
                    BeanUtils.copyProperties(e, vo);
                    return vo;
                }).map(e -> {
                    e.setChildren(getChildren(e, list));
                    // 如果children是空，就设为null
                    if (CollectionUtils.isEmpty(e.getChildren())) {
                        e.setChildren(null);
                    }
                    return e;
                }).collect(Collectors.toList());
    }

    @Override
    public CategoryBrandVo getCategoryAndBrandById(Long categoryId) {
        // 获取父级ID
        ShopProductCategory category = shopProductCategoryMapper.get(categoryId);
        Long parentId = category.getParentId();
        // 根据父级ID查询分类
        List<ShopProductCategory> categoryList = shopProductCategoryMapper.getByParentId(parentId);
        // 查询品牌
        List<ShopBrandCategory> brandCategoryList = shopBrandCategoryMapper.getByCategoryId(parentId);
        if (!CollectionUtils.isEmpty(brandCategoryList)) {
            List<Long> brandIds = brandCategoryList.stream().map(ShopBrandCategory::getBrandId).collect(Collectors.toList());
            List<ShopBrand> brandList = shopBrandMapper.getByIds(brandIds);
            return new CategoryBrandVo(categoryList, brandList);
        }
        return new CategoryBrandVo(categoryList, new ArrayList<>(0));
    }

}
